import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { Tag } from '../database/models';
import { utils } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 创建标签
 */
export async function createTag(ctx: Context): Promise<void> {
  const { name, color, description } = ctx.request.body as {
    name?: string;
    color?: string;
    description?: string;
  };

  if (!name) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签名称不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查标签是否已存在（同一用户下）
  const existingTag = await queryOne<Tag>(
    'SELECT * FROM tags WHERE user_id = ? AND name = ?',
    [userId, name]
  );

  if (existingTag) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签名称已存在');
    return;
  }

  // 创建标签
  const tagId = utils.generateUUID();
  await query(
    `INSERT INTO tags (id, user_id, name, color, description)
     VALUES (?, ?, ?, ?, ?)`,
    [tagId, userId, name, color || null, description || null]
  );

  const newTag = await queryOne<Tag>('SELECT * FROM tags WHERE id = ?', [tagId]);
  success(ctx, newTag);
}

/**
 * 更新标签
 */
export async function updateTag(ctx: Context): Promise<void> {
  const { id, name, color, description } = ctx.request.body as {
    id?: string;
    name?: string;
    color?: string;
    description?: string;
  };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查标签是否存在且属于当前用户
  const tag = await queryOne<Tag>('SELECT * FROM tags WHERE id = ? AND user_id = ?', [id, userId]);
  if (!tag) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签不存在');
    return;
  }

  // 如果更新名称，检查新名称是否已存在
  if (name && name !== tag.name) {
    const existingTag = await queryOne<Tag>(
      'SELECT * FROM tags WHERE user_id = ? AND name = ? AND id != ?',
      [userId, name, id]
    );
    if (existingTag) {
      error(ctx, ResponseCode.BAD_REQUEST, '标签名称已存在');
      return;
    }
  }

  // 更新标签信息
  const updates: string[] = [];
  const params: any[] = [];

  if (name !== undefined) {
    updates.push('name = ?');
    params.push(name);
  }
  if (color !== undefined) {
    updates.push('color = ?');
    params.push(color);
  }
  if (description !== undefined) {
    updates.push('description = ?');
    params.push(description);
  }

  if (updates.length > 0) {
    params.push(id, userId);
    await query(`UPDATE tags SET ${updates.join(', ')} WHERE id = ? AND user_id = ?`, params);
  }

  const updatedTag = await queryOne<Tag>('SELECT * FROM tags WHERE id = ? AND user_id = ?', [id, userId]);
  if (!updatedTag) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签不存在');
    return;
  }
  success(ctx, updatedTag);
}

/**
 * 删除标签
 */
export async function deleteTag(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  // 检查标签是否存在且属于当前用户
  const tag = await queryOne<Tag>('SELECT * FROM tags WHERE id = ? AND user_id = ?', [id, userId]);
  if (!tag) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签不存在');
    return;
  }

  // 删除标签关联关系
  await query('DELETE FROM blog_relations WHERE relation_type = ? AND relation_id = ?', ['tag', id]);

  // 删除标签
  await query('DELETE FROM tags WHERE id = ? AND user_id = ?', [id, userId]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询标签列表
 */
export async function getTagList(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 100, name } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    name?: string;
  };

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  let sql = 'SELECT * FROM tags WHERE user_id = ?';
  const params: any[] = [userId];

  if (name) {
    sql += ' AND name LIKE ?';
    params.push(`%${name}%`);
  }

  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const tags = await query<Tag>(sql, params);

  // 构建总数查询
  let countSql = 'SELECT COUNT(*) as count FROM tags WHERE user_id = ?';
  const countParams: any[] = [userId];
  
  if (name) {
    countSql += ' AND name LIKE ?';
    countParams.push(`%${name}%`);
  }

  const totalResult = await queryOne<{ count: number }>(countSql, countParams);

  success(ctx, {
    list: tags,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 查询标签详情
 */
export async function getTagDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as any;
  const userId = currentUser.id;

  const tag = await queryOne<Tag>('SELECT * FROM tags WHERE id = ? AND user_id = ?', [id, userId]);
  if (!tag) {
    error(ctx, ResponseCode.BAD_REQUEST, '标签不存在');
    return;
  }

  success(ctx, tag);
}

